package com.dwxt.community.service;

import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.OkHttpUtils;
import com.dwxt.community.dao.AppDataMapper;
import com.dwxt.community.dao.UserMapper;
import com.dwxt.community.entity.AppData;
import com.dwxt.community.entity.UserExample;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.Year;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TaskService {

    @Autowired
    private AppDataMapper appDataMapper;

    @Autowired
    private UserMapper userMapper;

    public void lookUserData() throws ParseException {
        int year = DateUtils.getYear(null);
        int month = DateUtils.getMonth(null);
        int day = DateUtils.getDay(null);
        String today = year + "-" + month + "-" + day;
        String nextDay = year + "-" + month + "-" + (day + 1);
        Date date = DateUtils.formatDate(today);
        Date next = DateUtils.formatDate(nextDay);
        Integer vipNum = selectVipNum(date, next);
        Integer actNum = selectActNum(date, next);
        Integer download = selectDownload();

        AppData appData =new AppData();
        appData.setYear(year);
        appData.setMonth(month);
        appData.setDay(day);
        appData.setNumber(vipNum);
        appData.setType(2);
        appDataMapper.insertSelective(appData);

        appData.setNumber(actNum);
        appData.setType(3);
        appDataMapper.insertSelective(appData);

        appData.setNumber(download);
        appData.setType(1);
        appDataMapper.insertSelective(appData);

    }

    private Integer selectDownload() {
        String url = "https://www.pgyer.com/apiv2/app/update";
        Map map = new HashMap();
        map.put("_api_key", "67626483635e8402676b4a67f00838e2");
        map.put("appKey", "42db2e4779f76633f950aa8df664c722");
        map.put("buildInstallType", "3");
        String s = OkHttpUtils.formPost(url, map, null);
        JSONObject jsonObject = JSONObject.fromObject(s);
        int code = jsonObject.getInt("code");
        if (code == 0) {
            int anInt = jsonObject.getJSONObject("data").getInt("todayDownloadCount");
            return anInt;
        } else {
            log.error("下载接口失败" + jsonObject);
        }
        return 0;
    }

    private Integer selectActNum(Date date, Date next) {
        UserExample example = new UserExample();
        example.createCriteria().andLastLoginTimeBetween(date, next);
        return ((Long) userMapper.countByExample(example)).intValue();
    }

    private Integer selectVipNum(Date today, Date next) {
        UserExample example = new UserExample();
        example.createCriteria().andCreateTimeBetween(today, next);
        return ((Long) userMapper.countByExample(example)).intValue();
    }
}
